package com.andyliu.configer;

import com.andyliu.system.entity.User;
import com.andyliu.system.service.IUserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.realm.SimpleAccountRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * ClassName: CustomRealm
 * Description: TODO
 * date: 2021/8/10 10:26 上午
 *
 * @author andyliu
 * @qq 115176513
 * @since JDK 1.8
 */
public class CustomRealm extends SimpleAccountRealm {
    @Autowired
    private IUserService userService;
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken to = (UsernamePasswordToken)token;
        String userName = to.getUsername();
        String pwd = new String(to.getPassword());
        User user = userService.getUserByLoginName(userName);
        if(user==null){
            throw new UnknownAccountException();
        }
        return new SimpleAuthenticationInfo(userName,user.getPassword(), ByteSource.Util.bytes(userName),getName());
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return super.doGetAuthorizationInfo(principals);
    }

    public void setUserService(IUserService userService) {
        this.userService = userService;
    }
}
